package com.yunxin.admin.system.api.core.customer;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.Result;
import com.yunxin.core.customer.domain.CustomerInfo;
import com.yunxin.core.customer.domain.CustomerTelephonerLog;
import com.yunxin.core.customer.dto.BatchOperationDistributionDto;
import com.yunxin.core.customer.dto.OperationCustomerChangeDto;
import com.yunxin.core.customer.dto.operationDistributionDto;
import com.yunxin.core.customer.service.CustomerInfoService;
import com.yunxin.core.customer.service.CustomerTelephonerLogService;
import com.yunxin.core.wechat.domain.WechatFollowCustomer;
import com.yunxin.core.wechat.service.WechatFollowCustomerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "15.重新分配")
@Slf4j
@RestController
@RequestMapping("/core/v1/customer/distribution")
@RequiredArgsConstructor
public class CustomerDistributionController {

    @Autowired
    @Lazy
    private CustomerInfoService customerInfoService;
    @Autowired
    @Lazy
    private CustomerTelephonerLogService customerTelephonerLogService;


    @Operation(summary = "重新分配话务员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/reassign")
    @PreAuthorize("@ss.hasPerm('boke:customer:reassign')")
    public Result<Boolean> reassign(@Validated @RequestBody operationDistributionDto dto) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        CustomerInfo customerInfo = customerInfoService.getById(dto.getCustomerId());
        if (ObjectUtils.isEmpty(customerInfo)){
            throw new BusinessException("没有该客户");
        }
        if (ObjectUtils.isEmpty(dto.getTeamId())){
            if (!SecurityUtils.X.isBokeMerchantUser()){
                return Result.failed("请确定团队");
            }
        }
//        if (ObjectUtils.isEmpty(dto.getSalesmanId())){
//            if (!SecurityUtils.X.isBokeMerchantUser()){
//                return Result.failed("请确定业务员");
//            }
//        }

        if (!ObjectUtils.isEmpty(customerInfo.getSalesmanId()) && customerInfo.getSalesmanId() != -1){
            if (customerInfo.getIsWechat()==1){
                if (customerInfo.getTeamId().intValue() != dto.getTeamId().intValue()){
                    return Result.failed("该客户关联企微客户 请勿重新分配");
                }
//                if (customerInfo.getSalesmanId().intValue() != dto.getSalesmanId().intValue()){
//                    return Result.failed("该客户关联企微客户 请勿重新分配业务员");
//                }
            }
        }
        dto.setOperator(userId.intValue());
        return Result.success(customerInfoService.reDistribution(dto,customerInfo));
    }

    @Operation(summary = "批量分配业务员和话务员", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/batchReassign")
    @PreAuthorize("@ss.hasPerm('boke:customer:reassign')")
    public Result<Map<String,String>> batchReassign(@Validated @RequestBody BatchOperationDistributionDto dto) {
        Long userId = SecurityUtils.X.getUser().getUserId();
        if (ObjectUtils.isEmpty(dto.getTeamId())){
            if (!SecurityUtils.X.isBokeMerchantUser()){
                return Result.failed("请确定团队");
            }
        }
//        if (ObjectUtils.isEmpty(dto.getSalesmanId())){
//            if (!SecurityUtils.X.isBokeMerchantUser()){
//                return Result.failed("请确定业务员");
//            }
//        }
        Map<String,String> result= new HashMap<>();
        List<CustomerInfo> customerInfos = customerInfoService.listByIds(dto.getCustomerIdList());
        if (ObjectUtils.isEmpty(customerInfos) || customerInfos.size()<1){
            return Result.failed("未找到客户资源");
        }
        List<CustomerInfo> newCustomerInfos = new ArrayList<>();
        for (int i=0;i<customerInfos.size();i++){
            CustomerInfo customerInfo = customerInfos.get(i);
            if (!ObjectUtils.isEmpty(customerInfo.getSalesmanId()) && customerInfo.getSalesmanId() != -1){
                if (customerInfo.getIsWechat()==1){
                    result.put(customerInfo.getName(),"该客户关联企微客户 请勿重新分配");
                    continue;
//                    if (!ObjectUtils.isEmpty(dto.getTeamId()) &&  customerInfo.getTeamId().intValue() != dto.getTeamId().intValue()){
//                        result.put(customerInfo.getName(),"该客户关联企微客户 请勿重新分配");
//                        continue;
//                    }
//                    if (ObjectUtils.isEmpty(dto.getSalesmanId())){
//                        result.put(customerInfo.getName(),"该客户关联企微客户 不能取消分配业务员");
//                        continue;
//                    }
//                    if (customerInfo.getSalesmanId().intValue() != dto.getSalesmanId().intValue()){
//                        result.put(customerInfo.getName(),"该客户关联企微客户 请勿重新分配业务员");
//                        continue;
//                    }
                }
            }
            newCustomerInfos.add(customerInfo);
        }
        dto.setOperator(userId.intValue());
        customerInfoService.batchReassign(dto,newCustomerInfos);
        return Result.success(result);
    }

    @Operation(summary = "解除分配", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/relieve")
    @PreAuthorize("@ss.hasPerm('boke:customer:relieve')")
    public Result<Boolean> relieve(@RequestParam("customerId") Long customerId) {

        Long userId = SecurityUtils.X.getUser().getUserId();
        return Result.success(customerInfoService.relieveDistribution(customerId,userId));

    }


    @Operation(summary = "话务员分配日志", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/listByCustomerId")
    //@PreAuthorize("@ss.hasPerm('boke:customer:relieve')")
    public Result<List<CustomerTelephonerLog>> listByCustomerId(@RequestParam("customerId") Long customerId) {
        return Result.success(customerTelephonerLogService.listByCustomerId(customerId));
    }


}
